package xupt.se.ttms.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xupt.se.ttms.dao.UserDAO;
import xupt.se.ttms.idao.DAOFactory;
import xupt.se.ttms.model.User;

@WebServlet(urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        String emp_no = request.getParameter("emp_no");
        String emp_pass = request.getParameter("emp_pass");
        User user = new User();
        user.setEmp_no(emp_no);
        user.setEmp_pass(emp_pass);
        UserDAO dao = (UserDAO) DAOFactory.creatUserDAO();
        int type = dao.login(user);
        if(type == 1)
        {
            // 管理员
            String emp_name = dao.findName(emp_no);
            User findUser = dao.findUser(emp_no);
            if(null == findUser)
                findUser = user;
            System.out.println("login--->" + findUser);
            request.getSession().setAttribute("user", findUser);
            request.getSession().setAttribute("emp_name", emp_name);
            request.getSession().setAttribute("emp_no", emp_no);
            request.getSession().setAttribute("emp_pass", emp_pass);
            request.getSession().setAttribute("login_flag", "ok");
            response.sendRedirect("employee/index1.jsp");
        }
        else
            if(type == 0)// 用户
            {
                String emp_name = dao.findName(emp_no);
                request.getSession().setAttribute("user", user);
                request.getSession().setAttribute("emp_name", emp_name);
                request.getSession().setAttribute("emp_no", emp_no);
                request.getSession().setAttribute("emp_pass", emp_pass);
                request.getSession().setAttribute("login_flag", "ok");
                System.out.println("普通用户登录.....");
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
            // 密码错误
            else
            {
                request.setAttribute("desc", "用户名、密码错误!");
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
    }
}
